<?php
namespace services;
class WxwithdrawalService{
    public function __construct() {
    }



    /**
     * @notes 商家转账到零钱
     */
    public function transfer($param)
    {
        //请求URL
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        //请求方式
        $http_method = 'POST';
        //请求参数
        $data = $param;
        // if ($withdrawApply['left_money'] >= 2000) {
        //     if (empty($withdrawApply['real_name'])) {
        //         throw new \Exception('转账金额 >= 2000元，收款用户真实姓名必填');
        //     }
        //     $data['transfer_detail_list'][0]['user_name'] = $this->getEncrypt($withdrawApply['real_name'],$config);
        // }
 
        $token  = $this->ttoken($url,$http_method,$data);//获取token
        $result = $this->https_request($url,json_encode($data),$token);//发送请求
        \think\Log::write('提现响应参数：'.$result);
        $result_arr = json_decode($result,true);
        //array(3) { ["batch_id"]=> string(42) "131000404057901691086842023051740318905563" ["create_time"]=> string(25) "2023-05-17T12:05:45+08:00" ["out_batch_no"]=> string(7) "zz77897" }
        return $result_arr;
 
        //批次受理成功，进行操作
 
 
        return true;
    }
 
    /**
     * @notes 获取签名
     */
    public function ttoken($url,$http_method,$data)
    {
        $timestamp   = time();//请求时间戳
        $url_parts   = parse_url($url);//获取请求的绝对URL
        $nonce       = $timestamp.rand('10000','99999');//请求随机串
        $body        = empty($data) ? '' : json_encode((object)$data);//请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];
 
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents(ROOT_PATH.config('cert_path'),false, stream_context_create($stream_opts)));
        $serial_no          = $apiclient_cert_arr['serialNumberHex'];//证书序列号
        $mch_private_key    = file_get_contents(ROOT_PATH.config('key_path'),false, stream_context_create($stream_opts));//密钥
        $merchant_id = config('msxgzh.mch_id');//商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message = $http_method."\n".
            $canonical_url."\n".
            $timestamp."\n".
            $nonce."\n".
            $body."\n";
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        $sign = base64_encode($raw_sign);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        return $schema.' '.$token;
    }
 
    /**
     * @notes 发送请求
     */
    public function https_request($url,$data,$token,$http_method='POST')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($http_method=='GET'){
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
        } else {
            curl_setopt($curl, CURLOPT_POST, 1);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [
            'Authorization:'.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if(!empty($headers)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
 
    /**
     * @notes 敏感信息加解密
     */
    public function getEncrypt($str)
    {
        //$str是待加密字符串
        $public_key = file_get_contents(config('cert_path'));
        $encrypted = '';
        if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
            //base64编码
            $sign = base64_encode($encrypted);
        } else {
            throw new \Exception('encrypt failed');
        }
        return $sign;
    }
 
    /**
     * @notes 商家明细单号查询
     * {"limit":20,"offset":0,"transfer_batch":{"appid":"wx78da405ec5b8a9b1","batch_id":"131000104001301691086842024051723540161213","batch_name":"吃喝不愁外卖试吃返利提现","batch_remark":"吃喝不愁外卖试吃返利提现","batch_status":"FINISHED","batch_type":"API","create_time":"2024-05-17T13:15:12+08:00","fail_amount":0,"fail_num":0,"mchid":"1644161646","out_batch_no":"506745349597","success_amount":2600,"success_num":1,"total_amount":2600,"total_num":1,"transfer_scene_id":"1001","update_time":"2024-05-17T13:15:22+08:00"},"transfer_detail_list":[{"detail_id":"132000104001301691086842024051749328557451","detail_status":"SUCCESS","out_detail_no":"506745349597"}]}
     */
    public function detailsQuery($batch_id)
    {
        //请求URL
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/batch-id/'.$batch_id.'?need_query_detail=true&offset=0&limit=20&detail_status=ALL';
        //请求方式
        $http_method = 'GET';
        //请求参数
        $data = [];
        // $token  = self::token($url,$http_method,$data,$config);//获取token
        $token  = $this->ttoken($url,$http_method,$data);//获取token
        // $result = self::https_request($url,$data,$token);//发送请求
        $result = $this->https_request($url,json_encode($data),$token,$http_method);//发送请求
        $result_arr = json_decode($result,true);
        return $result_arr;
    }


    // 获取平台证书列表
    public function certificates()
    {
        $url='https://api.mch.weixin.qq.com/v3/certificates';
        //请求方式
        $http_method = 'GET';
        //请求参数
        $data = [];
        // $token  = self::token($url,$http_method,$data,$config);//获取token
        $token  = $this->ttoken($url,$http_method,$data);//获取token
        // $result = self::https_request($url,$data,$token);//发送请求
        $result = $this->https_request($url,json_encode($data),$token,$http_method);//发送请求
        // $result_arr = json_decode($result,true);
        return $result;
    }

}
